<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="产品类型名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品类型名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-input-number v-model="queryParams.level" 
        controls-position="right" placeholder="请输入产品级别" clearable 
        @keyup.enter.native="handleQuery" :min="0" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plainicon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-if="refreshTable"
      v-loading="loading" 
      :data="productTypeList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="产品类型名称" prop="name" width="300" :show-overflow-tooltip="true" />
      <el-table-column label="级别" prop="level" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.kh_type_level" :value="scope.row.level"/>
        </template>  
      </el-table-column>
      <el-table-column label="排序" prop="sort" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:type:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditSeo(scope.row)">SEO设置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <seoDetail ref="seo" />

    <!-- 添加或修改产品类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24" v-if="form.id === undefined">
            <el-form-item label="上级产品类型" prop="parentId">
              <treeselect v-model="form.parentId" :options="productTypeOptions" :normalizer="normalizer" placeholder="选择上级产品类型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="产品类型名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入产品类型名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductType,listProductTypeExcludeChild,getProductType,addProductType,updateProductType,delProductType,getPids} from "@/api/product/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ProductType",
  dicts: ['kh_type_level'],
  components: { 
    Treeselect,
    seoDetail: () => import('@/views/content/seo/detail'),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品类型表格数据
      productTypeList: [],
      //父类编号
      pids:[],  
      // 产品类型树
      productTypeOptions:[],
      // 查询参数
      queryParams: {
        name: undefined,
        level: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品类型名称值不能为空", trigger: "blur" }
        ],
        parentId: [
           { required: true, message: "产品类型的父类型不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ]
      },
      seoData: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品类型列表 */
    getList() {
      this.loading = true;
      listProductType(this.queryParams).then(response => {
        this.productTypeList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        parentId: undefined,
        sort: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加产品类型";
      listProductType().then(response => {
        this.productTypeOptions = this.handleTree(response.data, "id");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id 
      getProductType(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品类型";

        listProductTypeExcludeChild(row.id).then(response => {
          this.productTypeOptions = this.handleTree(response.data, "id");
          if (this.productTypeOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.productTypeOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProductType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(function() {
          return delProductType(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },

     //获取父类pid下拉框内容
    changeSelect(val){
      getPids(val).then((res) => {
        this.pids = res.data
        //console.log(res.data)
      })
     },

     handleEditSeo(row) {
      this.seoData.pageType = 'productType',
      this.seoData.pageId = row.id;
      this.$refs.seo.open(this.seoData);
    },
  }
}
</script>